package com.easycms.common;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class EncryptUtils {
    private static String DesKey="#s^un2ye21fcv%|f0XpR,+vh";

    public static String Des(String text){

    try{
//        DESKeySpec desKeySpec = new DESKeySpec(DesKey.getBytes("ASCII"));
//        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
//        SecretKey securekey = keyFactory.generateSecret(desKeySpec);
        // 偏移量
        //IvParameterSpec iv = new IvParameterSpec(DesKey.getBytes("ASCII"));

        SecretKeySpec localSecretKeySpec = new SecretKeySpec(DesKey.getBytes("ASCII"), "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");   //这里指定了CBC模式. 如果是
        cipher.init(Cipher.ENCRYPT_MODE, localSecretKeySpec);
        //cipher.init(Cipher.ENCRYPT_MODE, securekey);
        // cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        byte[] data=cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(data);
        //return byte2Base64String(data);
    }catch (Exception ex){
        return ex.getMessage();
     }

    }

    //base64字符串转byte[]
    public static byte[] base64String2Byte(String base64Str){
        return Base64.decodeBase64(base64Str);
    }
    //byte[]转base64
    public static String byte2Base64String(byte[] b){
        return Base64.encodeBase64String(b);
    }
}
